package com.trytech.mongoocrawler.client;

import com.trytech.mongoocrawler.client.transport.http.CrawlerHttpRequest;
import com.trytech.mongoocrawler.client.transport.http.HttpClient;
import com.trytech.mongoocrawler.client.transport.http.WebResult;
import com.trytech.mongoocrawler.common.transport.protocol.*;

import java.util.UUID;

/**
 * @author jiangtao@meituan.com
 * @since: Created on 2018年04月10日
 */
public class UrlProtocolHandler extends ProtocolHandler {
    @Override
    protected AbstractProtocol doHandle(ProtocolFilterChain filterChain, AbstractProtocol abstractProtocol) throws Exception {
        if (abstractProtocol instanceof UrlProtocol) {
            UrlProtocol urlProtocol = (UrlProtocol) abstractProtocol;
            CrawlerHttpRequest request = new CrawlerHttpRequest(UUID.randomUUID().toString(), urlProtocol.getURL(), null, null);
            WebResult<String> webResult = HttpClient.doHtmlGet(request);
            HtmltextProtocol dataProtocol = new HtmltextProtocol();
            dataProtocol.setData(webResult.getData());
            dataProtocol.setUrl(urlProtocol.getUrl());
            dataProtocol.setTraceId(null);
            return dataProtocol;
        }
        return filterChain.doFilter(abstractProtocol);
    }

    @Override
    protected boolean checkProtocol(AbstractProtocol abstractProtocol) {
        return abstractProtocol instanceof UrlProtocol;
    }
}
